<template>
  <ul class="list">
<!--    touchstart触摸开始事件，touchmove接触点改变，滑动时，touchend触摸结束，手指离开屏幕时-->
    <li class="item"
        v-for="item in letters"
        :key="item"
        :ref="item"
        @click="handleLetterClick"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
    >{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      // 节流优化
      timer: null
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick (e) {
      // 向外触发一个事件，将点击的内容传递给父组件
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      // 触摸状态开始
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          // 计算滑动了多少个字母
          // 语法：element.offsetTop 返回一个整数，表示该元素的顶部偏移量，距离上方或上层控件的位置，单位是像素 px。
          // 被优化了成了this.startY
          // const startY = this.$refs['A'][0].offsetTop
          // clientY 事件属性返回当事件被触发时鼠标指针向对于浏览器页面（客户区）的垂直坐标
          // 计算touchY手指滑动触摸结束到的位置
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style scoped lang="stylus">
@import '~@styles/varibles.styl'
  .list
    display flex
    flex-direction column
    justify-content center
    position absolute
    top 1.58rem
    right 0
    bottom 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
</style>
